
import { asyncRoutes } from '@/router/routes'
import { cloneDeep } from 'lodash'
import router, { resetRouter } from '@/router'

// 确保默认值
const safeAsyncRoutes = asyncRoutes || []

/**
 * 使用meta.roles判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission (roles = [], route) {
  if (route.meta && route.meta.roles) {
    return Array.isArray(roles) && roles.some(role => route.meta.roles.includes(role))
  }
  return true
}

export function filterAsyncRoutes (routes = [], roles = []) {
  const res = []
  if (!Array.isArray(routes)) {
    console.error('filterAsyncRoutes: routes参数必须是数组', routes)
    return res
  }

  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.path === '/profile') {
      res.push(tmp)
      return
    }

    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: [],
  isRoutesLoaded: false,
  lastLoadedTime: null
}

const mutations = {
  SET_ROUTES: (state, routes = []) => {
    state.addRoutes = routes
    state.routes = routes
    state.isRoutesLoaded = true
    state.lastLoadedTime = new Date().getTime()
  },
  SET_ROUTES_LOADED: (state, loaded) => {
    state.isRoutesLoaded = loaded
    if (!loaded) {
      state.lastLoadedTime = null
    }
  }
}

const actions = {
  generateRoutes ({ commit, state }, roles = []) {
    return new Promise((resolve) => {
      console.log('[路由生成] 开始生成路由')
      let accessedRoutes = []

      try {
        if (!safeAsyncRoutes?.length) {
          throw new Error('无动态路由配置')
        }

        accessedRoutes = cloneDeep(safeAsyncRoutes)
        resetRouter()

        // 先添加404路由
        if (!router.hasRoute('404')) {
          router.addRoute({
            path: '*',
            redirect: '/404'
          })
        }

        // 添加业务路由
        const addedRoutes = []
        accessedRoutes.forEach(route => {
          try {
            if (!router.hasRoute(route.name)) {
              console.log(`[路由注入] 正在添加: ${route.path}`)
              router.addRoute(route)
              addedRoutes.push(route.path)

              if (route.children?.length) {
                route.children.forEach(child => {
                  if (!router.hasRoute(child.name)) {
                    router.addRoute(route.name, child)
                    addedRoutes.push(`${route.path}/${child.path}`)
                  }
                })
              }
            }
          } catch (e) {
            console.error(`[路由添加失败] ${route.path}:`, e)
          }
        })

        commit('SET_ROUTES', accessedRoutes)
        console.log('[路由生成] 完成:', addedRoutes)
        resolve(accessedRoutes)
      } catch (error) {
        console.error('[路由生成] 失败:', error)
        commit('SET_ROUTES_LOADED', false)
        resolve([])
      }
    })
  }
}

const getters = {
  routes: state => state.routes,
  addRoutes: state => state.addRoutes,
  isRoutesLoaded: state => state.isRoutesLoaded,
  shouldReloadRoutes: state => {
    return !state.isRoutesLoaded ||
           (state.lastLoadedTime && (Date.now() - state.lastLoadedTime > 300000)) // 5分钟缓存
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
